package org.tp8.sampleapp.view;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.bson.types.ObjectId;
import org.fusesource.hawtbuf.ByteArrayInputStream;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.tp8.sampleapp.dms.model.Attachment;
import org.tp8.sampleapp.dms.model.BookDoc;
import org.tp8.sampleapp.enums.CRUDAction;
import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.util.SampleAppLogger;
import org.tp8.sampleapp.view.util.SessionConstants;
import org.tp8.sampleapp.view.wrapper.AttachmentWrapper;

/**
 * The Class BookDocBean.
 */
@ManagedBean(name = "bookDocBean")
@RequestScoped()
public class BookDocBean extends AbstractDocBean<BookDoc> {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -5905217809579678523L;
	/**
	 * The Constant log.
	 */
	private final static SampleAppLogger log = new SampleAppLogger(
			BookDocBean.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#createNew()
	 */
	@Override
	protected BookDoc createNew() {
		return new BookDoc();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#findOne(java.lang.Long)
	 */
	@Override
	protected BookDoc findOne(String id) {
		BookDoc item;
		try {
			item = getBookFacade().findOne(id);
		} catch (SampleAppException e) {
			log.error(e);
			item = null;
		}
		return item;
	}

	/**
	 * Save.
	 * 
	 * @param item
	 *            the item
	 */
	public void save(BookDoc item) {
		FacesMessage message;
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			item.setAttachment(getAttachment(null));

			setItem(item);
			String id = getBookFacade().save(item);
			clearAttachment(false);
			item.setId(ObjectId.massageToObjectId(id));
			message = new FacesMessage("Successfully saved");
		} catch (Exception e) {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"There was an error during saving.", e.getMessage());
		}

		context.addMessage(null, message);
	}

	/**
	 * Delete.
	 * 
	 * @param id
	 *            the id
	 */
	public void delete(String id) {
		FacesMessage message;
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			getBookFacade().delete(id);
			message = new FacesMessage("Successfully deleted");
		} catch (SampleAppException e) {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"There was an error during deletion.", e.getMessage());
		}

		context.addMessage(null, message);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#findAll()
	 */
	@Override
	public Collection<BookDoc> findAll() {
		Collection<BookDoc> list;
		try {
			list = getBookFacade().findAll();
		} catch (SampleAppException e) {
			log.error(e);
			list = new LinkedList<>();
		}
		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.tp8.sampleapp.view.AbstractDocBean#processFileUpload(java.lang.String
	 * , byte[], java.lang.String)
	 */
	@Override
	public void processFileUpload(String filename, byte[] content,
			String mimetype) throws SampleAppException {
		Attachment attachment = new Attachment();
		attachment.setFilename(filename);
		attachment.setMimeType(mimetype);
		attachment.setData(content);

		// BookDoc book = getItem();
		// book.setAttachment(attachment);

		// Store in session
		AttachmentWrapper wrapper = new AttachmentWrapper(attachment,
				CRUDAction.INSERT);
		getSessionMap().put(SessionConstants.ΒΟΟΚ_UPLOADED_ATTACHMENT, wrapper);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractDocBean#clearAttachment()
	 */
	public void clearAttachment(boolean delete) {
		AttachmentWrapper wrapper;
		if (delete) {
			wrapper = new AttachmentWrapper(null, CRUDAction.DELETE);
		} else {
			wrapper = null;
		}
		getSessionMap().put(SessionConstants.ΒΟΟΚ_UPLOADED_ATTACHMENT, wrapper);
	}

	/**
	 * Download attachment.
	 * 
	 * @return the streamed content
	 */
	public StreamedContent downloadAttachment() {
		Attachment attachment = null;
		FacesMessage msg = null;

		String attachmentId = (String) getRequestParam("attachmentId");
		getItem().setAttachmentId(ObjectId.massageToObjectId(attachmentId));

		try {
			attachment = getAttachment(attachmentId);
		} catch (IOException e) {
			log.error(e);
			msg = new FacesMessage("Error downloading attachment");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		StreamedContent streamedContent = null;
		if (attachment != null) {
			streamedContent = new DefaultStreamedContent(
					new ByteArrayInputStream(attachment.getData()),
					attachment.getMimeType(), attachment.getFilename());
		}

		return streamedContent;
	}

}
